package com.analytical.www.pop

import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.analytical.www.R
import com.analytical.www.component.SoundPoolManager
import com.analytical.www.databinding.PopInputSampleBinding
import com.analytical.www.util.StringUtils.log
import com.analytical.www.util.UtilFastClickAbort

/**
 * @author shawn
 * @since 2023/5/18
 */
class PopInputSample(context: Context) : PopBase(context) {
    private lateinit var mContext: Context
    private var binding:PopInputSampleBinding
    var listener:IActionListener? = null
    init {
        mContext = context
        setBackgroundDrawable(null)
        val view = LayoutInflater.from(context).inflate(R.layout.pop_input_sample, null)
        contentView = view
        binding = PopInputSampleBinding.bind(view)

        // 获取焦点拉起软键盘
        binding.etInput.requestFocus()


        binding.btnOk.setOnClickListener {
            if(UtilFastClickAbort.isFastClick()){
                return@setOnClickListener
            }
            hideSoftInput()
            SoundPoolManager.showSound(R.raw.tap_button)
            val input = binding.etInput.text.toString().trim()
            listener?.onActionOk(input)
            dismiss()
        }
        binding.btnNo.setOnClickListener {
            if(UtilFastClickAbort.isFastClick()){
                return@setOnClickListener
            }
            hideSoftInput()
            SoundPoolManager.showSound(R.raw.tap_button)
            listener?.onActionNo()
            dismiss()
        }
    }

    fun show(parent:View) {
        binding.etInput.postDelayed({
            val imm = mContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(binding.etInput, InputMethodManager.SHOW_FORCED)
            "弹出软键盘代码".log()
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
        },100)
        showAtLocation(parent,Gravity.NO_GRAVITY,0,0)
    }

    private fun hideSoftInput() {
        val imm = mContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(binding.root?.windowToken, 0)
    }

    interface IActionListener {
        fun onActionOk(input:String)
        fun onActionNo()
    }

}